<template>
    <div class="group-chats">
        <div v-for="group in groups" :key="group.id">
            <card @click.native="toDetail(group.id)">
                <div slot="content" class="card-padding">
                    <p class="group-title">{{group.title}}</p>
                    <p class="group-msg">
                        <template v-if="group.last_msg">
                            <span>{{group.last_msg.content | tran}}</span>
                        </template>
                        <template v-else>
                            <span>开始聊天</span>
                        </template>
                    </p>
                </div>
            </card>
        </div>
        <infinite-loading :on-infinite="onInfinite" ref="infiniteLoading">
            <span slot="no-results">
                <divider>我是有底线的</divider>
            </span>
            <span slot="no-more">
                <divider>不要在扯了</divider>
            </span>
        </infinite-loading>


    </div>
</template>
<script>
     import {Group, Card, dateFormat,Divider, Swipeout, SwipeoutItem, SwipeoutButton} from 'vux'
import InfiniteLoading from 'vue-infinite-loading'
export default {
    components: {
        Card,
            Group,
            InfiniteLoading,
            Divider,
            Swipeout,
            SwipeoutItem,
            SwipeoutButton
    },
filters: {
        tran(val) {
            if (val) {
                return val.slice(0, 44)
            } 
            return val
        }
    },

        data() {
            return {
                groups: [],
                page: {next_page: 0}
            }
        },

    created() {
        this.$store.commit("storeNotify", false)  
        this.$store.commit("storeState", false)  
        },
    methods: {
        onInfinite() {
            this.$http.get("chats.json", {params: {page: this.page.next_page}}).then(res => {
                let data = res.data
                if (data.chats.length) {
                    this.groups = this.groups.concat(data.chats);
                    this.page = data.page
                    this.$refs.infiniteLoading.$emit("$InfiniteLoading:loaded");
                    if (this.groups.length / 50 === 10 || data.page.next_page == null) {
                        this.$refs.infiniteLoading.$emit("$InfiniteLoading:complete");
                    } 
                } else {
                    this.$refs.infiniteLoading.$emit("$InfiniteLoading:complete");
                }
            })
        },
            toDetail(id){
                this.$router.push({name: "chat", params: {id: id}})
            },
            

        }
    }
</script>
<style>
    .card-padding {
        padding: 10px;
    }
</style>
